package com.yangjun.service.report;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.Collator;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yangjun.common.DVConstants;
import com.yangjun.common.ServerResponse;
import com.yangjun.common.comparator.TargetItemComparator;
import com.yangjun.common.comparator.TargetItemComparatorByTargetArr;
import com.yangjun.common.excel.DataBaseExcelContext;
import com.yangjun.common.excel.ExcelExportResult;
import com.yangjun.dao.mybatis.mapper.report.DvReportSearchTmpMapper;
import com.yangjun.dao.mybatis.mapper.report.ProductInfoReportExportMapper;
import com.yangjun.dao.mybatis.mapper.report.ReportDownloadStatusMapper;
import com.yangjun.dao.mybatis.mapper.report.ReportExportStatusMapper;
import com.yangjun.dao.mybatis.mapper.report.ReportImportStatusMapper;
import com.yangjun.dao.mybatis2.mapper.common.CommonMapper;
import com.yangjun.entity.report.DvExcelFieldDefinitionEntity;
import com.yangjun.entity.report.DvReportDownloadStatusEntity;
import com.yangjun.entity.report.DvReportExportStatus;
import com.yangjun.entity.report.DwKadBaseWareDEntity;
import com.yangjun.po.report.ProductInfoReportExportPO;
import com.yangjun.service.common.CommonService;
import com.yangjun.service.permission.ReportExportPermissionService;
import com.yangjun.utils.DvDateUtils;
import com.yangjun.utils.DvUtils;
import com.yangjun.utils.POIExcelUtils;
import com.yangjun.vo.report.ProductInfoReportExportVO;
import com.yangjun.vo.report.ProductInfoReportManageVO;
@Service
public class ProductInfoReprotExportService  {
	@Value("${excel.uploadPath}")
    private String uploadPath;
	@Value("${excel.downloadPath}")
    private String downloadPath;
	@Autowired
	private DataBaseExcelContext context;
	
	private final static String reporttype = "productInfo";
	@Autowired
	private ProductInfoReportExportMapper productInfoReportExportMapper;
	@Autowired
	private ReportExportStatusMapper reportExportStatusMapper;
	@Autowired
	private ReportImportStatusMapper reportImportStatusMapper;
	@Autowired
	private DvReportSearchTmpMapper dvReportSearchTmpMapper;
	@Autowired
	private ReportDownloadStatusMapper reportDownloadStatusMapper;
	@Autowired
	private ReportCommonService reportCommonService;
	@Autowired
	private ReportExportPermissionService reportExportPermissionService;
	@Autowired
	private CommonService commonService;
 	@Autowired
 	private CommonMapper commonMapper;
	/**
	 * @Description 获取维度信息
	 * @return
	 * @author yangjun
	 * @Date 2017年7月5日 上午11:50:06
	 */
	public Object getDeminsion(String reportid,String userid){
		ProductInfoReportExportVO pireVo = null;
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		
		String[] departmentValue1SelectData = null;
		String[] statusSelectData = null;
		String[] waretypeSelectData = null;
		String[] stockstatusSelectData = null;
		String[] audittypeSelectData = null;
		String[] targetSelectData  = null;
		//修改报表排序号的字段顺序
		List<Map<String,Object>> sortTargetSelectData=Lists.newArrayList();
		String reportName = "商品信息-";
		String departmentName = "faCategory";
		String uploadFileId = "";
		String uploadFileName = "";
		String searchName = "";
		String date = DvDateUtils.getDate(new Date(), 0);
		
		if(dvReportExportStatus!=null){
			pireVo = JSON.parseObject(dvReportExportStatus.getReportparam(), ProductInfoReportExportVO.class);
			departmentName = pireVo.getDepartmentName();
			departmentValue1SelectData = pireVo.getDepartmentValue1();
			statusSelectData = pireVo.getStatus();
			waretypeSelectData = pireVo.getWaretype();
			stockstatusSelectData = pireVo.getStockstatus();
			audittypeSelectData = pireVo.getAudittype();
			targetSelectData = pireVo.getTarget();
			reportName = pireVo.getReportName();
			uploadFileId = pireVo.getUploadFileId();
			if(StringUtils.isNotBlank(uploadFileId)){
				uploadFileName = reportImportStatusMapper.queryReportStatusByUUID(uploadFileId).getReportName();
			}
			searchName = pireVo.getSearchName();
		}
		Map<String,Object> demensionMap = Maps.newHashMap();
		demensionMap.put("reportName",reportName);
		demensionMap.put("departmentName",departmentName);
		demensionMap.put("faCategory", commonService.HandleCheackBoxStatus(productInfoReportExportMapper.queryFinancialCategory(),departmentValue1SelectData));
		demensionMap.put("department", commonService.HandleCheackBoxStatus(productInfoReportExportMapper.queryDepartment(),departmentValue1SelectData));
		demensionMap.put("tmDepartment", commonService.HandleCheackBoxStatus(productInfoReportExportMapper.queryTMDepartment(),departmentValue1SelectData));
		Comparator<Object> cmp = Collator.getInstance(java.util.Locale.CHINA);
		List<String> gspCategoryList = productInfoReportExportMapper.queryGSPCategory();
		Collections.sort(gspCategoryList,cmp);
		demensionMap.put("gspCategory", commonService.HandleCheackBoxStatus(gspCategoryList,departmentValue1SelectData));
		demensionMap.put("type1", commonService.HandleCheackBoxStatus(productInfoReportExportMapper.queryWareTypeName1(),departmentValue1SelectData));
		demensionMap.put("status", commonService.HandleCheackBoxStatus(Arrays.asList(DVConstants.STATUS),statusSelectData));
		demensionMap.put("waretype", commonService.HandleCheackBoxStatus(Arrays.asList(DVConstants.WARETYPE),waretypeSelectData));
		demensionMap.put("stockstatus", commonService.HandleCheackBoxStatus(Arrays.asList(DVConstants.STOCKSTATUS),stockstatusSelectData));
		demensionMap.put("audittype", commonService.HandleCheackBoxStatus(Arrays.asList(DVConstants.AUDITTYPE),audittypeSelectData));
		demensionMap.put("date", date);
		demensionMap.put("uploadFileName", uploadFileName);
		demensionMap.put("uploadFileId", uploadFileId);
		
		List<DvExcelFieldDefinitionEntity> excelFieldDefinitionList = reportCommonService.getExcelFieldDefinitionList(reporttype);
		//获取每个报表的指标分类
		Map<String,String> tmpCategoryMap = reportCommonService.queryCategory(reporttype);
		List<Map<String,String>> categoryList = Lists.newArrayList();
		
		Map<String,List<Map<String,Object>>> targetMap = Maps.newHashMap();
		List<Map<String,Object>> targetList =null;
		for(Map.Entry<String,String> categoryEntry: tmpCategoryMap.entrySet()){
			//初始化指标分类数组
			Map<String,String> categoryMap = Maps.newHashMap();
			categoryMap.put("name", categoryEntry.getKey());
			categoryMap.put("value", categoryEntry.getValue());
			categoryList.add(categoryMap);
			//初始化指标分类内容
			targetList = Lists.newArrayList();
			targetMap.put(categoryEntry.getKey(),targetList);
		}
		demensionMap.put("category", categoryList);
				
		//查询有权限显示的报表字段
		String[] allowFieldArr = reportExportPermissionService.getReportAllowField(userid, reporttype);
		if(allowFieldArr!=null&&allowFieldArr.length>0){
			for(DvExcelFieldDefinitionEntity excelFieldDefinitionEntity : excelFieldDefinitionList){
				//权限控制能够显示的字段，如果查询不到对应角色的权限直接不显示字段。
				//&&("18".equals(userid)||"507".equals(userid)||"715".equals(userid)||"6".equals(userid)||"518".equals(userid)||"141".equals(userid))
				if(allowFieldArr!=null){
					List<String> allowFieldList = Arrays.asList(allowFieldArr);
					if(!allowFieldList.contains(excelFieldDefinitionEntity.getEntityName())){
						continue;
					}
				}
				//封装默认的指标格式
				String categoryId = excelFieldDefinitionEntity.getCategoryId();
				if(StringUtils.isNotBlank(categoryId)){
					String entityName = excelFieldDefinitionEntity.getEntityName();
					String title = excelFieldDefinitionEntity.getTitle();
					int sort = excelFieldDefinitionEntity.getFieldSort();
					Map<String,Object> itemMap = Maps.newHashMap();
					itemMap.put("value", entityName);
					itemMap.put("name", title);
					itemMap.put("sort", sort);
					itemMap.put("checked", false);
					if(targetSelectData!=null){
						for(int i=0,len=targetSelectData.length;i<len;i++){
							if(entityName.equals(targetSelectData[i])){
								itemMap.put("checked", true);
								//修改报表排序号的字段顺序
								sortTargetSelectData.add(itemMap);
							}
						}						
					}
					targetList = targetMap.get(categoryId);
					//已经在上面初始化了不用判断空
					targetList.add(itemMap);
				}
			}
			for(Map.Entry<String,List<Map<String,Object>>> targetItemEntry : targetMap.entrySet()){
				Collections.sort(targetItemEntry.getValue(),new TargetItemComparator());
			}
		}
		demensionMap.put("reporttype", reporttype);
		demensionMap.put("target", targetMap);
		
		String[] searchWayNameArr = {"商品编码","商品名称","条形码","批准文号"};
		String[] searchWayValueArr = {"wareCode","wareName","barCode","registrationnumber"};
		List<Map<String,String>> searchWayList = Lists.newArrayList();
		for(int i = 0,len=searchWayNameArr.length;i<len;i++){
			Map<String,String> searchMap = Maps.newHashMap();
			searchMap.put("searchWayName", searchWayNameArr[i]);
			searchMap.put("searchWayValue", searchWayValueArr[i]);
			searchWayList.add(searchMap);
		}

		demensionMap.put("search", searchWayList);
		demensionMap.put("searchName", searchName);
		Collections.sort(sortTargetSelectData, new TargetItemComparatorByTargetArr(targetSelectData));
		demensionMap.put("sortTarget", sortTargetSelectData);
		reportCommonService.deleteUploadReport(userid);
		return ServerResponse.createBySuccess(demensionMap);
	}
	//获取二级类目
	public Object getType2(String[] type1,String reportid){
		ProductInfoReportExportVO pireVo = null;
		List<String> cheackBoxNameList = null;
		String[] type2 = null;
		
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		if(dvReportExportStatus!=null){
			pireVo = JSON.parseObject(dvReportExportStatus.getReportparam(), ProductInfoReportExportVO.class);
			type2 = pireVo.getDepartmentValue2();
		}
		if(type1!=null&&type1.length>0){
			cheackBoxNameList = productInfoReportExportMapper.queryWareTypeName2(type1);
		}
		return ServerResponse.createBySuccess(commonService.HandleCheackBoxStatus(cheackBoxNameList,type2));
	}
	public Object queryData(String reportid){
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		ProductInfoReportExportVO pireVo = JSON.parseObject(dvReportExportStatus.getReportparam(), ProductInfoReportExportVO.class);
		return queryData(pireVo);
	}
	public Object queryData(ProductInfoReportExportVO pireVo){
		Map<String,Object> resultMap = Maps.newHashMap();
		pireVo.setDate(DvDateUtils.getDate(new Date(), 0));

		String[] targetArr = pireVo.getTarget();
		List<String> targetList = getDefaultTargetList(targetArr);

		List<DvExcelFieldDefinitionEntity>  reportFieldDefinition= reportCommonService.getExcelFieldDefinitionList(reporttype);
		//装载表格数据
		List<List<String>> tableList = Lists.newArrayList();

		List<String> titleList = Lists.newArrayList();
		for(String item : targetList){
			for(DvExcelFieldDefinitionEntity definition : reportFieldDefinition){
				String name = definition.getEntityName();
				if(item.equals(name)){
					titleList.add(definition.getTitle());
				}
			}
		}
		tableList.add(titleList);
		//查找附件内容作为搜索条件
		if(StringUtils.isNotBlank(pireVo.getUploadFileId())){
			int partSize=1000;
			List<String> searchItemList = Lists.newArrayList();
			String fileName = reportImportStatusMapper.queryReportStatusByUUID(pireVo.getUploadFileId()).getFileName();
			System.out.println(fileName);
			File uploadFile = new File(uploadPath+fileName);
			FileInputStream readStream = null;
			try {
				readStream = new FileInputStream(uploadFile);
				List<List<Object>> datas =POIExcelUtils.readExcel(readStream, 0);
				for(int i=0,len=datas.size();i<len;i++){
					if(i>0&&datas.get(i).get(0)!=null){
						searchItemList.add(datas.get(i).get(0).toString());
					}
				}
				dvReportSearchTmpMapper.deleteDvReportSearchTmp(pireVo.getUserid());
				if(searchItemList.size()>partSize){
					int part = searchItemList.size()/partSize;
					for(int i=0;i<part;i++){
						List<String> tmpList  = searchItemList.subList(0, partSize);
						dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(pireVo.getUserid(), tmpList);
						searchItemList.subList(0, partSize).clear();
					}
				}
				if(searchItemList.size()>0){
					dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(pireVo.getUserid(), searchItemList);
				}
				pireVo.setSearchValue(searchItemList.size()>0?searchItemList.toArray(new String[searchItemList.size()]):null);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		ProductInfoReportExportPO productInfoReportExportPO = new ProductInfoReportExportPO();
		BeanUtils.copyProperties(pireVo, productInfoReportExportPO);
		productInfoReportExportPO.setSqlFieldStr(reportCommonService.getSqlFieldString(reporttype,targetList.toArray(new String[targetList.size()])));
		int type = reportExportPermissionService.getManagerType(productInfoReportExportPO.getUserid(), reporttype);
		//商品经理过滤 有数据就去掉之前的逻辑否则不用。
		List<String> names = commonMapper.getNoFilterGoodsManager(productInfoReportExportPO.getUsername());
		if(names!=null && names.size()>0){
			type = 1;
		}
		List<DwKadBaseWareDEntity> wareList = productInfoReportExportMapper.queryProductInfo(productInfoReportExportPO,1,10,type);
		JSONArray objectArr = JSON.parseArray(JSONObject.toJSONString(wareList));
		for(int i = 0,len = objectArr.size() ; i<len ; i++){
			JSONObject object = objectArr.getJSONObject(i);
			List<String> itemList = Lists.newArrayList();
			for(String item : targetList){
				itemList.add(object.getString(item)==null?"":object.getString(item));
			}
			tableList.add(itemList);
		}
		//报表数据行数
		resultMap.put("tableData", tableList);
		resultMap.put("rownum", wareList.size()>0?wareList.get(0).getCountNum():0);
		return ServerResponse.createBySuccess(resultMap);
	}
	public Object addDownloadTask(String reportid,HttpServletRequest request){
		DvReportExportStatus dvReportExportStatus = reportExportStatusMapper.queryReportStatusByReportId(reportid);
		ProductInfoReportExportVO pireVo = JSON.parseObject(dvReportExportStatus.getReportparam(), ProductInfoReportExportVO.class);
		return download(pireVo,request);
	}
	
	public Object addDownloadTask(ProductInfoReportExportVO pireVo,HttpServletRequest request){
		if(reportDownloadStatusMapper.queryReportByName(pireVo.getUserid(), pireVo.getReportName())>0){
			return ServerResponse.createByErrorMessage("已存在相同名称的报表，请重新命名!");
		}else{
			return download(pireVo,request);
		}
	}
	public Object download(ProductInfoReportExportVO pireVo,HttpServletRequest request){
		context.initDBExcelDefinitionReader("export");
		String[] targetArr = pireVo.getTarget();
		List<String> targetList = getDefaultTargetList(targetArr);
		pireVo.setDate(DvDateUtils.getDate(new Date(), 0));
		//mybatis无法判断数组长度
		List<String> searchItemList = Lists.newArrayList();
		if(StringUtils.isNotBlank(pireVo.getUploadFileId())){
			int partSize=1000;
			String fileName = reportImportStatusMapper.queryReportStatusByUUID(pireVo.getUploadFileId()).getFileName();
			File uploadFile = new File(uploadPath+fileName);
			FileInputStream readStream = null;
			try {
				readStream = new FileInputStream(uploadFile);
				List<List<Object>> datas =POIExcelUtils.readExcel(readStream, 0);
				for(int i=0,len=datas.size();i<len;i++){
					if(i>0&&datas.get(i).get(0)!=null){
						searchItemList.add(datas.get(i).get(0).toString());
					}
				}
				dvReportSearchTmpMapper.deleteDvReportSearchTmp(pireVo.getUserid());
				if(searchItemList.size()>partSize){
					int part = searchItemList.size()/partSize;
					for(int i=0;i<part;i++){
						List<String> tmpList  = searchItemList.subList(0, partSize);
						dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(pireVo.getUserid(), tmpList);
						searchItemList.subList(0, partSize).clear();
					}
				}
				if(searchItemList.size()>0){
					dvReportSearchTmpMapper.insertDvReportSearchTmpByBatch(pireVo.getUserid(), searchItemList);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		pireVo.setSearchValue(searchItemList.size()>0?searchItemList.toArray(new String[searchItemList.size()]):null);
		ProductInfoReportExportPO productInfoReportExportPO = new ProductInfoReportExportPO();
		
		//用户ID，UUID组成下载ID
		String downloadId = pireVo.getUserid()+UUID.randomUUID().toString().replaceAll("-", "");
		String downloadReportName = pireVo.getReportName();
		String fileName =downloadId+downloadReportName+".xlsx";

		DvReportDownloadStatusEntity dvReportDownloadStatusEntity = new DvReportDownloadStatusEntity();
		dvReportDownloadStatusEntity.setDownloadId(downloadId);
		dvReportDownloadStatusEntity.setFileName(fileName);
		dvReportDownloadStatusEntity.setReportName(downloadReportName);
		dvReportDownloadStatusEntity.setReportType(reporttype);
		dvReportDownloadStatusEntity.setUserid(pireVo.getUserid());
		dvReportDownloadStatusEntity.setUsername(pireVo.getUsername());
		dvReportDownloadStatusEntity.setUserrealname(pireVo.getUserrealname());
		dvReportDownloadStatusEntity.setTargetName(JSON.toJSONString(reportCommonService.getTargetNameList(targetArr, reporttype)));
		dvReportDownloadStatusEntity.setIp(DvUtils.getIp(request));
		
		BeanUtils.copyProperties(pireVo, productInfoReportExportPO);
		productInfoReportExportPO.setSqlFieldStr(reportCommonService.getSqlFieldString(reporttype,targetList.toArray(new String[targetList.size()])));
		int type = reportExportPermissionService.getManagerType(productInfoReportExportPO.getUserid(), reporttype);
		//商品经理过滤 有数据就去掉之前的逻辑否则不用。
		List<String> names = commonMapper.getNoFilterGoodsManager(productInfoReportExportPO.getUsername());
		if(names!=null && names.size()>0){
			type = 1;
		}
		int rownum = productInfoReportExportMapper.queryProductInfoCount(productInfoReportExportPO,type);
		if(reportDownloadStatusMapper.insertReport(dvReportDownloadStatusEntity)>0){
			DownloadTask downloadTask = new DownloadTask(fileName,targetList,rownum,productInfoReportExportPO,dvReportDownloadStatusEntity,type);
			new Thread(downloadTask).start();  
			return ServerResponse.createBySuccessMessage("加入下载列表成功！");
		}else{
			return ServerResponse.createByErrorMessage("加入下载列表失败！");
		}
	}
	
	class DownloadTask implements Runnable{
		public  boolean flag = true;  

		private String fileName;
		private Integer rownum;
		private List<String> targetList;
		private ProductInfoReportExportPO productInfoReportExportPO;
		private DvReportDownloadStatusEntity dvReportDownloadStatusEntity;
		private int type;
		public DownloadTask(String fileName,List<String> targetList,int rownum,ProductInfoReportExportPO productInfoReportExportPO,DvReportDownloadStatusEntity dvReportDownloadStatusEntity,int type){
			this.fileName = fileName;
			this.rownum = rownum;
			this.productInfoReportExportPO = productInfoReportExportPO;
			this.dvReportDownloadStatusEntity = dvReportDownloadStatusEntity;
			this.type = type;
			this.targetList = targetList;
		}
		public void stopThread(){
			flag = false;
		}
		@Override
		public void run() {
			while (flag){
				Long start = System.currentTimeMillis();
				OutputStream ops = null;
				ExcelExportResult exportResult = null;
				try {
					ops = new FileOutputStream(downloadPath+fileName);
					exportResult = context.createEmptyExcelForPart(reporttype,DwKadBaseWareDEntity.class,targetList);
					int pageSize = 40000;
					int totalPage = (int)Math.ceil(rownum/pageSize);
					totalPage += rownum%pageSize>0?1:0; 
					for(int i=1;i<=totalPage;i++){
						exportResult.append(productInfoReportExportMapper.queryProductInfo(productInfoReportExportPO,i,pageSize,type));
					}
				Workbook workbook = exportResult.build();
				workbook.write(ops);
				ops.close();
				workbook.close();
				dvReportDownloadStatusEntity.setEndDate(new Date());
				dvReportDownloadStatusEntity.setTimeConsume(Math.round(dvReportDownloadStatusEntity.getEndDate().getTime()-dvReportDownloadStatusEntity.getBeginDate().getTime())/1000);
				dvReportDownloadStatusEntity.setDownloadFlag(1);
				reportDownloadStatusMapper.updateReportById(dvReportDownloadStatusEntity);
				Long end = System.currentTimeMillis();
				System.out.println("ID:"+dvReportDownloadStatusEntity.getUserid()+" 名字:"+dvReportDownloadStatusEntity.getUsername()+"的用户进行下载,"+rownum+"行数据共花费："+(end-start)/1000+"秒,共"+totalPage+"页");
				this.stopThread();
				} catch (Exception e) {
					System.out.println("ProductInfoReprot awaitTermination interrupted: " + e);  
					this.stopThread();
				}
			}
		}
	}
	
	public Object addOrUpdateReport(ProductInfoReportExportVO pireVo){
		String reportid = pireVo.getReportid();
		List<String> targetNameList = Lists.newArrayList();
		String[] targetArr = pireVo.getTarget();

		List<DvExcelFieldDefinitionEntity> excelFieldDefinitionList = reportCommonService.getExcelFieldDefinitionList(reporttype);
		for(String target : targetArr){
			for(DvExcelFieldDefinitionEntity dvExcelFieldDefinitionItem : excelFieldDefinitionList){
				String entityName = dvExcelFieldDefinitionItem.getEntityName();
				String targetName = dvExcelFieldDefinitionItem.getTitle();
					if(target.equals(entityName)){
						targetNameList.add(targetName);
					}
			}
		}
		ProductInfoReportManageVO productInfoReportManageVO = new ProductInfoReportManageVO();
		BeanUtils.copyProperties(pireVo, productInfoReportManageVO);
		productInfoReportManageVO.setReportid(reportid);
		productInfoReportManageVO.setTargetName(targetNameList);
		productInfoReportManageVO.setSaveTime(DvDateUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
		if(StringUtils.isNotBlank(pireVo.getUploadFileId())){
			String uploadFileName = reportImportStatusMapper.queryReportStatusByUUID(pireVo.getUploadFileId()).getReportName();
			pireVo.setUploadFileName(uploadFileName);
			productInfoReportManageVO.setUploadFileName(pireVo.getUploadFileName());
		}
		if(StringUtils.isNotBlank(reportid)){
			DvReportExportStatus dvReportExportStatus = new DvReportExportStatus();
			dvReportExportStatus.setReportid(reportid);
			dvReportExportStatus.setReportName(pireVo.getReportName());
			dvReportExportStatus.setReportparam(JSON.toJSONString(pireVo));
			dvReportExportStatus.setReportManageParam(JSON.toJSONString(productInfoReportManageVO));

			if(reportExportStatusMapper.updateReportStatus(dvReportExportStatus)>0){
				return ServerResponse.createBySuccessMessage("修改报表成功!");
			}else{
				return ServerResponse.createBySuccessMessage("修改报表失败!");
			}
		}else{
			//加入报表前需要根据用户ID，报表名去判断是否有重名的报表
			if(reportExportStatusMapper.queryReport(pireVo.getUserid(), pireVo.getReportName())>0){
				return ServerResponse.createByErrorMessage("已存在相同名称的报表，请重新命名!");
			}else{
				reportid = reporttype+String.valueOf(System.currentTimeMillis())+String.valueOf((int)((Math.random()*9+1)*100000));
				pireVo.setReportid(reportid);
				productInfoReportManageVO.setReportid(reportid);
				pireVo.setDate(DvDateUtils.getDate(new Date(), 0));
				DvReportExportStatus dvReportExportStatus = new DvReportExportStatus();
				BeanUtils.copyProperties(pireVo, dvReportExportStatus);
				dvReportExportStatus.setCreatetime(new Date());
				dvReportExportStatus.setReportparam(JSON.toJSONString(pireVo));
				dvReportExportStatus.setReporttype(reporttype);
				dvReportExportStatus.setReportManageParam(JSON.toJSONString(productInfoReportManageVO));
				dvReportExportStatus.setFileName(pireVo.getUploadFileId()+pireVo.getUploadFileName());
				if(reportExportStatusMapper.insertReportStatus(dvReportExportStatus)>0){
					return ServerResponse.createBySuccessMessage("添加报表成功!");
				}else{
					return ServerResponse.createByErrorMessage("添加报表失败!");
				}
			}
		}
	}
	private List<String> getDefaultTargetList(String[] targetArr){
		List<String> targetList = Lists.newArrayList();
		String[] defaultArr = new String[]{"warecode"};
		for(String defaultItem : defaultArr){
			targetList.add(defaultItem);
		}
		for(String targetItem : targetArr){
			targetList.add(targetItem);
		}
		return targetList;
	}
}
